package com.changgou.fescar.interceptor;

import com.alibaba.fescar.core.context.RootContext;
import com.changgou.fescar.config.FescarAutoConfiguration;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;

/**
 * @Author: HuangFu
 * @Date: 2020/2/16 15:26
 * @Description: Fescar微服务拦截器
 */
@Component
public class FescarRestInterceptor implements RequestInterceptor, ClientHttpRequestInterceptor {
    /**
     * 每次请求其他微服务的时候，都将XID携带过去
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        //获取xid
        String xid = RootContext.getXID();
        if(!StringUtils.isEmpty(xid)){
            //设置微服务请求头FESCAR_XID
            template.header(FescarAutoConfiguration.FESCAR_XID,xid);
        }
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        String xid = RootContext.getXID();
        if(StringUtils.isNotEmpty(xid)){
            HttpHeaders headers = request.getHeaders();
            headers.put(FescarAutoConfiguration.FESCAR_XID, Collections.singletonList(xid));
        }
        //执行请求
        return execution.execute(request,body);
    }
}
